package com.learn.project2.service.admin.role;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.learn.project2.bean.MarketRole;
import com.learn.project2.bean.MarketRoleExample;
import com.learn.project2.mapper.MarketRoleMapper;
import com.learn.project2.mapper.admin.role.RoleMapper;
import com.learn.project2.model.bo.admin.role.*;
import com.learn.project2.model.vo.admin.RoleListVO;
import com.learn.project2.model.vo.admin.role.RoleCreateVO;
import com.learn.project2.model.vo.admin.role.RoleOptionsVO;
import com.learn.project2.model.vo.admin.role.RolePermissionsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Classname RoleServiceImpl
 * @Description
 * @author王茁
 * @Date 2022/1/6 22:18
 */
@Service
//@CacheConfig(cacheNames = {"marketRole"})
public class RoleServiceImpl implements RoleService {
    @Autowired
    MarketRoleMapper roleMapper;

    @Autowired
    RoleMapper roleMapperOnce;

    @Override
    /**
     * @description: TODO 查询  本机校验
     * @author wangzhuo
     * @date 2022-01-07 21:34
     * @version 1.0
     */
    // @Cacheable
    public RoleListVO list(Integer page, Integer limit, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        MarketRoleExample roleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        roleExample.setOrderByClause(sort + "\n" + order);
        List<MarketRole> marketRoles = roleMapper.selectByExample(roleExample);
        PageInfo<MarketRole> pageInfo = new PageInfo<>(marketRoles);
        RoleListVO roleListVO = new RoleListVO();
        roleListVO.setLimit(limit);
        roleListVO.setPage(page);
        roleListVO.setTotal((int) pageInfo.getTotal());
        roleListVO.setPages(pageInfo.getPages());
        roleListVO.setList(pageInfo.getList());
        return roleListVO;
    }

    @Override
    /**
     * @description: TODO 添加 本机校验
     * @author wangzhuo
     * @date 2022-01-07 21:34
     * @version 1.0
     */
    public RoleCreateVO create(RoleCreateBO roleCreateBO) {
        MarketRole marketRole = new MarketRole();
        marketRole.setName(roleCreateBO.getName());
        marketRole.setDesc(roleCreateBO.getDesc());
        marketRole.setEnabled(true);
        marketRole.setAddTime(new Date());
        marketRole.setDeleted(false);

        try {
            int insert = roleMapper.insert(marketRole);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        RoleCreateVO roleCreateVO = new RoleCreateVO();
        MarketRoleExample roleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andNameEqualTo(marketRole.getName());
        List<MarketRole> roleList = roleMapper.selectByExample(roleExample);
        for (MarketRole role : roleList) {
            roleCreateVO.setId(role.getId());
        }
        roleCreateVO.setName(marketRole.getName());
        roleCreateVO.setDesc(marketRole.getDesc());
        if (marketRole.getAddTime() != null) {
            roleCreateVO.setAddTime(marketRole.getAddTime().toString());
        }
        if (marketRole.getUpdateTime() != null) {
            roleCreateVO.setUpdateTime(marketRole.getAddTime().toString());
        }
        return roleCreateVO;
    }

    @Override
    /**
     * @description: TODO 删除 deleted 0->1  本机校验
     * @author wangzhuo
     * @date 2022-01-07 21:34
     * @version 1.0
     */
    public void delete(RoleDeleteBO roleDeleteBO) {
        //roleMapper.delete(roleDeleteBO.getId());
        MarketRole marketRole = new MarketRole();
        marketRole.setDeleted(true);
        MarketRoleExample roleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdEqualTo(roleDeleteBO.getId());
        roleMapper.updateByExampleSelective(marketRole, roleExample);
    }

    @Override
    /**
     * @description: TODO 修改 本机校验
     * @author wangzhuo
     * @date 2022-01-07 21:35
     * @version 1.0
     */
    public int update(RoleUpDateBO roleUpDateBO) {

        //roleMapper.update(roleUpDateBO);
        MarketRole marketRole = new MarketRole();
        marketRole.setUpdateTime(new Date());
        marketRole.setName(roleUpDateBO.getName());
        marketRole.setDesc(roleUpDateBO.getDesc());
        MarketRoleExample roleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdEqualTo(roleUpDateBO.getId());
        int i = roleMapper.updateByExampleSelective(marketRole, roleExample);
        if (i != 0) {
            return 200;
        }
        return 404;
    }

    @Override
    /**
     * @description: TODO 管理员option  本地校验
     * @author wangzhuo
     * @date 2022-01-08 10:05
     * @version 1.0
     */
    //  @Cacheable
    public RoleOptionsVO getOptions() {

        // List<RoleOptionsListBeanBO> optionsList = roleMapper.getOptionsList();

        //查找market_role表中deleted=0 的所有id,name
        MarketRoleExample roleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<MarketRole> optionsList = roleMapper.selectByExample(roleExample);
        List<RoleOptionsListBeanBO> roleOptionsListBeanBOList = new ArrayList<>();
        for (MarketRole marketRole : optionsList) {
            RoleOptionsListBeanBO roleOptionsListBeanBO = new RoleOptionsListBeanBO();
            roleOptionsListBeanBO.setLabel(marketRole.getName());
            roleOptionsListBeanBO.setValue(marketRole.getId());
            roleOptionsListBeanBOList.add(roleOptionsListBeanBO);
        }
        RoleOptionsVO roleOptionsVO = new RoleOptionsVO();
        PageInfo<MarketRole> pageInfo = new PageInfo<>(optionsList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        roleOptionsVO.setTotal((int) total);
        roleOptionsVO.setPages(pages);
        roleOptionsVO.setLimit((int) total);
        roleOptionsVO.setPage(pages);
        roleOptionsVO.setList(roleOptionsListBeanBOList);
        return roleOptionsVO;
    }

    @Override
    /**
     * @description: TODO 获取授权列表
     * @author wangzhuo
     * @date 2022-01-08 17:37
     * @version 1.0
     */
    public RolePermissionsVO getPermissions(Integer roleId) {

        RolePermissionsVO rolePermissionsVO = new RolePermissionsVO();
        //1.获取一级权限信息
        List<RolePermissionsFatherBO> permissionsFatherBOList = roleMapperOnce.getPermissionsFather(roleId);
        //1.创建 father信息list
        List<RolePermissionsVO.SystemPermissionsBean> fatherList = new ArrayList<>();
        for (RolePermissionsFatherBO rolePermissionsFatherBO : permissionsFatherBOList) {
            Integer fatherId = rolePermissionsFatherBO.getFatherId();
            //2.获取二级权限信息
            List<RolePermissionsSonBO> permissionsSonBOList = roleMapperOnce.getPermissionsSon(fatherId);
            //2.创建 son信息list
            List<RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX> sonList = new ArrayList<>();
            for (RolePermissionsSonBO rolePermissionsSonBO : permissionsSonBOList) {
                Integer sonId = rolePermissionsSonBO.getSonId();
                //3.获取三级权限信息
                List<RolePermissionsGrandsonBO> permissionsGrandson = roleMapperOnce.getPermissionsGrandson(sonId);
                //3.创建 grandSon信息list
                List<RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean> grandsonList = new ArrayList<>();
                for (RolePermissionsGrandsonBO rolePermissionsGrandsonBO : permissionsGrandson) {
                    RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean childrenBean = new RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean();
                    //3.将三级权限信息分别封装到每个childrenBean对象中
                    childrenBean.setId(rolePermissionsGrandsonBO.getGrandSonName());
                    childrenBean.setLabel(rolePermissionsGrandsonBO.getDetailLabel());
                    //method+api拼接
                    childrenBean.setApi(rolePermissionsGrandsonBO.getMethod() + rolePermissionsGrandsonBO.getApi());
                    grandsonList.add(childrenBean);
                }
                //2.将二级权限信息分别封装到每个ChildrenBeanX对象中
                RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX childrenBeanX = new RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX();
                childrenBeanX.setId(rolePermissionsSonBO.getSonName());
                childrenBeanX.setLabel(rolePermissionsSonBO.getSonLabel());
                childrenBeanX.setChildren(grandsonList);
                sonList.add(childrenBeanX);
            }

            RolePermissionsVO.SystemPermissionsBean systemPermissionsBean = new RolePermissionsVO.SystemPermissionsBean();
            //1.将一级权限信息分别封装到每个SystemPermissionsBean对象中
            systemPermissionsBean.setId(rolePermissionsFatherBO.getFatherName());
            systemPermissionsBean.setLabel(rolePermissionsFatherBO.getFatherLabel());
            systemPermissionsBean.setChildren(sonList);
            fatherList.add(systemPermissionsBean);
        }
        //获取enable=1的所有三级权限信息
       // List<String> strings = roleMapperOnce.selectPermissionsGrandsonByEnable(roleId);
        List<String> strings=new ArrayList<>();
        if(roleId==1) {
            //超级管理员
            strings = roleMapperOnce.selectPermissionsGrandsonByEnable(roleId);
        }else if(roleId==2) {
            //商场管理员
            strings = roleMapperOnce.selectPermissionsGrandsonByEnable2();
        }else if(roleId==3) {
            //roleId==3推广管理员
            strings = roleMapperOnce.selectPermissionsGrandsonByEnable3();
        }else {
            strings = roleMapperOnce.selectPermissionsGrandsonByEnable4();
        }
  /*      List<String> assignedList = new ArrayList<>();
        for (String string : strings) {
            //把/都变成：   admin/index/read -> admin:order:list
            String[] split = string.split("/");
            String assigned = split[0] + ":" + split[1] + ":" + split[2];
            assignedList.add(assigned);
        }
        rolePermissionsVO.setAssignedPermissions(assignedList);*/
        rolePermissionsVO.setAssignedPermissions(strings);
        rolePermissionsVO.setSystemPermissions(fatherList);
        return rolePermissionsVO;
    }

    @Override
    /**
     * @description: TODO
     * @author wangzhuo  PostRolePermissionsGrandsonBO
     * @date 2022-01-08 21:16
     * @version 1.0
     */
    public void postPermissions(PostRolePermissionBO postRolePermissionBO) {
        int roleId = postRolePermissionBO.getRoleId();
        List<String> permissions = postRolePermissionBO.getPermissions();
   /*     List<String> apiList = new ArrayList<>();
        //把:都变成/   admin:order:list -> admin/index/read
        for (String permission : permissions) {
            String[] split = permission.split(":");
            String api = split[0] + "/" + split[1] + "/" + split[2];
            apiList.add(api);
        }
        for (String api : apiList) {
            int i = roleMapperOnce.changeEnableForRolePermissionsGrandson(api);
            System.out.println(i);
        }*/
        for (String permission : permissions) {
            int i = roleMapperOnce.changeEnableForRolePermissionsGrandson(permission);
        }
    }
}
